package com.vicente.managerdemo.controller;

import com.vicente.managerdemo.common.ResultBean;
import com.vicente.managerdemo.dto.RoleQueryDto;
import com.vicente.managerdemo.dto.RoleVO;
import com.vicente.managerdemo.dto.UserRoleDto;
import com.vicente.managerdemo.entity.Menu;
import com.vicente.managerdemo.entity.Role;
import com.vicente.managerdemo.service.RoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 系统角色表 前端控制器
 * </p>
 *
 * @author vicente
 * @since 2024-12-04
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    /**
     * @Description: 分页查询角色信息
     **/
    @PostMapping("/page")
    public ResultBean getPageRole(@RequestBody RoleQueryDto queryDto) {
        return roleService.queryPage(queryDto);
    }

    /**
     * @Description: 保存或更新用户数据
     **/
    @PostMapping("/save")
    public ResultBean save(@RequestBody Role role) {
        if (role.getRoleId() == null) {
            return roleService.insertRole(role);
        }
        return roleService.updateRole(role);
    }

    /**
     * @Description: 删除用户数据
     **/
    @DeleteMapping("/delete/{id}")
    public ResultBean deleteByPrimaryKey(@PathVariable int id) {
        return roleService.deleteById(id);
    }

    /**
     * @Description: 获取所有用户数据
     **/
    @GetMapping("all")
    public ResultBean getAllRoles() {
        return roleService.getAllRoles();
    }

    /**
     * @Description: 根据角色id查询该角色下的已添加用户
     **/
    @RequestMapping("/listUserIds/{roleId}")
    public ResultBean listUserIdsByRoleId(@PathVariable Long roleId){
        List<Long> userIds = roleService.listUserIdsByRoleId(roleId);
        return ResultBean.getSuccess(userIds);
    }

    /**
     * @Description: 保存用户角色关联数据
     **/
    @RequestMapping("/saveUserRole")
    public ResultBean saveUserRole(@RequestBody UserRoleDto userRoleDto){
        roleService.saveUserRole(userRoleDto.getRoleId(),userRoleDto.getReceiverIds());
        return ResultBean.getSuccess();
    }

    /**
     * @Description: 获取角色下的菜单
     **/
    @RequestMapping("/listMenusByRoleId/{roleId}")
    public ResultBean listMenusByRoleId(@PathVariable Long roleId){
        List<Menu> menus = roleService.listMenusByRoleId(roleId);
        return ResultBean.getSuccess(menus);
    }

    /**
     * @Description: 保存角色数据和角色菜单数据，包含新增和修改
     **/
    @RequestMapping("/saveRoleAndRoleMenu")
    public ResultBean saveRoleAndRoleMenu(@RequestBody RoleVO sysRoleVO){
        boolean roleNameUnique = roleService.checkRoleNameUnique(sysRoleVO);
        boolean roleKeyUnique = roleService.checkRoleKeyUnique(sysRoleVO);

        if (roleNameUnique && roleKeyUnique){
            roleService.saveRoleAndRoleMenu(sysRoleVO);
            return ResultBean.getSuccess();
        }else {
            return ResultBean.getFail("角色名称或权限字符重复！");
        }
    }

}
